﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Duellum.Core;
using Duellum.Map;
using Duellum.Wpf2d.Plugin;
using JpLabs.Geometry;

namespace Duellum.Wpf.Edit
{
	//CheckboxList = http://alexshed.spaces.live.com/blog/cns!71C72270309CE838!133.entry

	public class DeleteEntriesEventArgs : EventArgs
	{
		public DeleteEntriesEventArgs(IEnumerable<IDuelMapEntry> entries)
		{
			Entries = entries;
		}
		
		public IEnumerable<IDuelMapEntry> Entries { get; private set; }
	}

	public partial class CellEditor : UserControl
	{
		private PointInt cellPosition;
		private DuelMap map;

		public CellEditor()
		{
			InitializeComponent();

			this.CommandBindings.Add(new CommandBinding(
			    ApplicationCommands.SelectAll,
			    (s, ev) => {
					if (itemList.SelectedItems.Count == itemList.Items.Count) {
						itemList.UnselectAll();
					} else {
						itemList.SelectAll();
					}
				},
			    (s, ev) => {ev.CanExecute = this.itemList.HasItems;}
			));
			
			this.CommandBindings.Add(new CommandBinding(
			    ApplicationCommands.Delete,
			    (s, ev) => {
					OnDeleteEntries(itemList.SelectedItems.Cast<FrameworkElement>().Select(o => (IDuelMapEntry)o.Tag));
					//itemList.SelectedItems
					//    .Cast<FrameworkElement>()
					//    .Select(o => (IDuelMapEntry)o.Tag)
					//    .ForEach(e => this.mapViewer.Map.RemoveEntry(e));
					//this.Inspect();
					//this.mapViewer.Redraw();
			    },
			    (s, ev) => {ev.CanExecute = this.itemList.SelectedItems.Count > 0;}
			));
		}
		
		//public DuelType SelectedType { get; set; }
		
		public event EventHandler<DeleteEntriesEventArgs> DeleteEntries;
		
		protected virtual void OnDeleteEntries(IEnumerable<IDuelMapEntry> entries)
		{
			var handler = DeleteEntries;
			if (handler != null) handler(this, new DeleteEntriesEventArgs(entries));
		}
		
		public void Inspect(PointInt cellPosition, DuelMap map)
		{
			this.cellPosition = cellPosition;
			this.map = map;
			
			Inspect();
		}
		
		public void Clear()
		{
			imgThumbnail.Source = null;
		}
		
		private void Inspect()
		{
			//panel.Children.Clear();
			
			var domain = App.Current.CurrentDomain;
			var wpf2d = domain.GetPlugin<Wpf2dPlugin>(); //Wpf2dPlugin.Current;
			
			var entries	= map.Query(cellPosition).ToArray();
			var objects = entries.Select(e => e.Object);
			//var ground	= objects.Where(o => o.IsGround()).SingleOrDefault();
			//var first	= objects.Where(o => !o.IsGround()).FirstOrDefault();
			
			{
				//var text = string.Concat("Selected Position: ", cellPosition.ToString());
				//panel.Children.Add(new TextBlock(new Run(text)) { FontWeight = FontWeights.Bold });
				lblPosition.Text = cellPosition.ToString();
			}
			
			{
				//var drawingGroup = new DrawingGroup();
				//var imgSource = new DrawingImage(drawingGroup);
				
				//using (var dc = drawingGroup.Open()) {
				//    const double zoom = 2;
				//    var hexSize = wpf2d.HexSize;
				//    var atOriginRect = new Rect(new Point(0, 0), hexSize);

				//    var borderImg
				//        = (ground != null)
				//        ? wpf2d.GetHexBorderImg(zoom)
				//        : wpf2d.GetEmptyHexImg(cellPosition.Z, mapViewer.Map.GroundLevel, zoom);
				//    dc.DrawImage(borderImg, atOriginRect);
					
				//    if (ground != null) {
				//        var groundImg = wpf2d.GetImage(ground);
				//        if (groundImg != null) dc.DrawImage(groundImg, atOriginRect);
				//    }
					
				//    if (first != null) {
				//        dc.DrawImage(
				//            wpf2d.GetImage(first),
				//            atOriginRect
				//        );
				//    }
				//}
				//imgSource.Freeze();
				
				//var img = new Image() { MaxWidth = 64, Source = imgSource };
				//panel.Children.Add(img);
				const double zoom = 2;
				imgThumbnail.Source = wpf2d.GetImage(objects, cellPosition, map.GroundLevel, zoom); //imgSource;
			}

			if (!entries.Any()) {
				//var text = "Empty";
				//panel.Children.Add(new TextBlock(new Run(text)));
				//lblSummary.Text = "Empty";
				lblSummary.Visibility = Visibility.Visible;
				itemList.ItemsSource = null;
			} else {
				{
					//var text = string.Concat("Objects: ", objects.Count());
					//panel.Children.Add(new TextBlock(new Run(text)));
					//lblSummary.Text = text;
					lblSummary.Visibility = Visibility.Collapsed;
				}
				
				/*				
				const string radioButtonGroup = "entries";
				//var radioButtonGroup = Guid.NewGuid().ToString();
				
				bool isFirst = true;

				foreach (var entry in entries) {
					//var type = (DuelType)entry.Object;
					//var text = type.Id.ToString();
					//var text = string.Concat("Obj id='", obj.Type.Id, "'");
					string text = ItemDesc(entry.Object);
					var radio = new RadioButton() {
						GroupName = radioButtonGroup,
						Tag = entry
					};
					radio.Checked += EntryRadio_Checked;
					radio.Content = new TextBlock(new Run(text));
					panel.Children.Add(radio);
					if (isFirst) {
						isFirst = false;
						radio.IsChecked = true;
					}
				}
				{
					var deleteBtn = new Button() { Content = "Delete" };
					deleteBtn.Click += ((s,e) => {
						if (this.selectedEntry != null) {
							this.mapViewer.Map.RemoveEntry(selectedEntry);
							this.Inspect();
							this.mapViewer.Redraw();
						}
					});
					panel.Children.Add(deleteBtn);
				}
				/*/
				itemList.ItemsSource = entries.Select(
					e => new ContentControl() {
						Content = ItemDesc(e.Object),
						Tag = e
					}
				);
				itemList.SelectAll();//SelectedIndex = 0;
				//*/
			}
		}
		
		private static string ItemDesc(DuelAbstraction dObj)
		{
			return (dObj is BaseDuelObj) ? string.Concat("Obj id='", dObj.Id, "'") : (string)dObj.Id;
		}

		//void EntryRadio_Checked(object sender, RoutedEventArgs e)
		//{
		//    selectedEntry = (IDuelMapEntry)((FrameworkElement)sender).Tag;
		//}
	}
}
